package cn.sdhuijin.mediaplatform;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import cn.sdhuijin.mediaplatform.components.CustomVideoView;
import cn.sdhuijin.mediaplatform.utils.DateFormatUtil;
import cn.sdhuijin.mediaplatform.utils.DirMaker;
import cn.sdhuijin.mediaplatform.utils.ToolsUtil;
import cn.sdhuijin.mediaplatform.utils.TxtUtil;

/**
 * @author sunp@sdhuijin.cn:
 * @version 创建时间：2015年3月23日 下午5:48:30 类说明
 */
public class MainActivity extends Activity implements OnClickListener,
		MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener,
		MediaPlayer.OnPreparedListener {

	private Button btn_app;
	private Button btn_wap;
	private Button btn_install;
	private TextView tv_time;
	private CustomVideoView vv_video;
	private static final int msgKey1 = 1;
	private int mPositionWhenPaused = -1;
	private int currentShowVideo = 0;
	private WebView wv_rate;
	private List<String> videoList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		btn_app = (Button) findViewById(R.id.btn_app);
		btn_app.setOnClickListener(this);
		btn_wap = (Button) findViewById(R.id.btn_wap);
		btn_wap.setOnClickListener(this);
		btn_install = (Button) findViewById(R.id.btn_install);
		btn_install.setOnClickListener(this);
		tv_time = (TextView) findViewById(R.id.tv_time);
		vv_video = (CustomVideoView) findViewById(R.id.vv_videoView);
		vv_video.setOnPreparedListener(this);
		vv_video.setOnErrorListener(this);
		vv_video.setOnCompletionListener(this);
		wv_rate = (WebView) findViewById(R.id.wv_rate);

		videoList = DirMaker.getFiles(Environment.getExternalStorageDirectory()
				.getPath() + "/playlist/video");

		wv_rate.getSettings().setDefaultTextEncodingName("UTF-8");
		String content = TxtUtil.readTxtFile(Environment
				.getExternalStorageDirectory().getPath()
				+ "/playlist/txt/lilv.txt");
		Log.e("利率", content);

		wv_rate.loadDataWithBaseURL(
				"",
				"<html><head><title></title></head><body><marquee scrollamount=2 direction=left><FONT face=楷体_GB2312 color=#ff0000 size=5>"
						+ content + "</FONT></marquee></body></html>",
				"text/html", "UTF-8", "");
		new TimeThread().start();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			final EditText inputPassword = new EditText(this);
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("进入管理端")
					.setIcon(android.R.drawable.ic_dialog_info)
					.setView(inputPassword)
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
								}
							});
			builder.setPositiveButton("确认",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							String pwd = inputPassword.getText().toString();
							if (pwd.equals("zqnx")) {
								Intent intent = new Intent(MainActivity.this,
										SeetingActivity.class);
								MainActivity.this.startActivity(intent);
							} else {
								Toast.makeText(MainActivity.this, "您输入的密码不正确！",
										Toast.LENGTH_LONG).show();
							}
						}
					});
			builder.show();
			return true;
		} else
			return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v) {
		int id = (Integer) v.getId();
		Intent intent = new Intent();
		switch (id) {
		case R.id.btn_app:
			// 启动农信APP应用
			PackageInfo packageInfo;
			try {
				packageInfo = this.getPackageManager().getPackageInfo(
						"com.android.clock.sd", 0);
			} catch (NameNotFoundException e) {
				packageInfo = null;
				e.printStackTrace();
			}
			if (packageInfo == null) {
				Toast.makeText(this, "山东省农村信用社客户端暂时不可用，感谢您对我行的支持！",
						Toast.LENGTH_LONG).show();
			} else {
				intent.setComponent(new ComponentName("com.android.clock.sd",
						"com.android.clock.sd.activty.IndexActivity"));
				intent.setAction(Intent.ACTION_VIEW);
				startActivity(intent);
			}
			break;
		case R.id.btn_wap:
			// 启动农信WAP网页
			if (ToolsUtil.isNetworkConnected(this)) {
				intent.setClass(this, WebViewActivity.class);
				startActivity(intent);
			} else {
				Toast.makeText(this, "网络尚未接通，暂时无法使用网上银行！", Toast.LENGTH_LONG)
						.show();
			}
			break;
		case R.id.btn_install:
			intent.setClass(this, InstallActivity.class);
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	public class TimeThread extends Thread {
		@Override
		public void run() {
			do {
				try {
					Thread.sleep(1000);
					Message msg = new Message();
					msg.what = msgKey1;
					mHandler.sendMessage(msg);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} while (true);
		}
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case msgKey1:
				String str = DateFormatUtil.currentDateAndWeekAndTime();
				tv_time.setText(str);
				break;
			default:
				break;
			}
		}
	};

	@Override
	public void onStart() {
		if (videoList.size() > 0) {
			vv_video.setVideoPath(videoList.get(currentShowVideo));
			vv_video.start();
		}
		super.onStart();
	}

	@Override
	public void onPause() {
		mPositionWhenPaused = vv_video.getCurrentPosition();
		vv_video.stopPlayback();
		super.onPause();
	}

	@Override
	public void onResume() {
		if (mPositionWhenPaused >= 0) {
			vv_video.seekTo(mPositionWhenPaused);
			mPositionWhenPaused = -1;
		}
		super.onResume();
	}

	@Override
	public void onCompletion(MediaPlayer arg0) {
		vv_video.stopPlayback();
		arg0.release();
		playNext();
	}

	@Override
	public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
		Toast.makeText(this, "文件不存在或者格式不支持", Toast.LENGTH_LONG).show();
		vv_video.stopPlayback();
		arg0.release();
		return true;
	}

	@Override
	public void onPrepared(MediaPlayer arg0) {
	}

	private void playNext() {
		if (++currentShowVideo >= videoList.size()) {
			currentShowVideo = 0;
		}
		vv_video.setVideoPath(videoList.get(currentShowVideo));
		vv_video.start();
	}
}
